package com.zxy.zxyrpc.registry;

import com.zxy.zxyrpc.model.ServiceMetaInfo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 注册中心服务本地缓存
 *
 * @author zxy
 * @since 2025/5/18
 **/
public class RegistryServiceCache {
    // 服务缓存（多节点，但不完善）
    private final Map<String, List<ServiceMetaInfo>> serviceMetaInfoMap = new ConcurrentHashMap<>();

    /**
     * 写缓存
     */
    public void writeCache(String serviceKey, List<ServiceMetaInfo> serviceMetaInfoList) {
        serviceMetaInfoMap.put(serviceKey, serviceMetaInfoList);
    }

    /**
     * 写入缓存子节点
     * */
    public void writeNodeCache(String serviceKey, ServiceMetaInfo serviceMetaInfo) {
        List<ServiceMetaInfo> serviceMetaInfoList = serviceMetaInfoMap.get(serviceKey);
        serviceMetaInfoList.add(serviceMetaInfo);
    }

    /**
     * 读缓存
     */
    public List<ServiceMetaInfo> readCache(String serviceKey) {
        return serviceMetaInfoMap.get(serviceKey);
    }

    /**
     * 删除缓存
     */
    public void removeServiceCache(String serviceKey) {
        serviceMetaInfoMap.remove(serviceKey);
    }

    /**
     * 删除缓存子节点
     * */
    public void removeServiceNodeCache(String serviceKey, String serviceNodeKey) {
        List<ServiceMetaInfo> serviceMetaInfoList = serviceMetaInfoMap.get(serviceKey);
        serviceMetaInfoList.removeIf(serviceMetaInfo -> serviceNodeKey.equals(serviceMetaInfo.getServiceNodeKey()));
    }

    /**
     * 缓存清空
     */
    public void clearCache() {
        serviceMetaInfoMap.clear();
    }

    /**
     * 缓存是否包含 serviceKey
     */
    public boolean containsKey(String serviceKey) {
        return serviceMetaInfoMap.containsKey(serviceKey);
    }

    /**
     * 缓存中是否包含 serviceNodeKey
     */
    public boolean containsCache(String serviceKey, String serviceNodeKey) {
        List<ServiceMetaInfo> serviceMetaInList = serviceMetaInfoMap.get(serviceKey);
        if (serviceMetaInList == null)
            return false;
        for (ServiceMetaInfo serviceMetaInfo : serviceMetaInList) {
            if (serviceNodeKey.equals(serviceMetaInfo.getServiceNodeKey())) {
                return true;
            }
        }
        return false;
    }
}
